<template>
  <div class="page-container">
    <div class="page-header">
      <h2>学生管理</h2>
      <div class="header-actions">
        <div class="search-box">
          <input type="text" v-model="searchKeyword" placeholder="搜索学生姓名或学号" @input="handleSearch" />
          <select v-model="filterGrade" @change="handleSearch">
            <option value="">全部年级</option>
            <option value="初一">初一</option>
            <option value="初二">初二</option>
          </select>
          <select v-model="filterClass" @change="handleSearch">
            <option value="">全部班级</option>
            <option value="1">1班</option>
            <option value="2">2班</option>
          </select>
        </div>
        <button class="btn btn-primary" @click="openStudentDialog()">添加学生</button>
      </div>
    </div>

    <div class="students-container">
      <table class="student-table" v-if="filteredStudents.length">
        <thead>
          <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>班级</th>
            <th>联系电话</th>
            <th>家长姓名</th>
            <th>家长电话</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="student in filteredStudents" :key="student.id">
            <td>{{ student.studentId }}</td>
            <td>{{ student.name }}</td>
            <td>{{ student.gender === 'male' ? '男' : '女' }}</td>
            <td>{{ student.age }}</td>
            <td>{{ student.grade }}{{ student.class }}班</td>
            <td>{{ student.phone }}</td>
            <td>{{ student.parentName }}</td>
            <td>{{ student.parentPhone }}</td>
            <td>
              <span class="status-tag" :class="student.status">
                {{ getStatusText(student.status) }}
              </span>
            </td>
            <td class="actions">
              <button class="btn-icon" @click="openStudentDialog(student)">
                <i class="icon">✏️</i>
              </button>
              <button class="btn-icon" @click="deleteStudent(student)">
                <i class="icon">🗑️</i>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-else class="empty-state">
        <p>暂无学生数据</p>
      </div>
    </div>

    <!-- 学生信息表单对话框 -->
    <div class="dialog-overlay" v-if="showStudentDialog" @click="closeStudentDialog">
      <div class="dialog-content" @click.stop>
        <h3>{{ isEdit ? '编辑学生' : '添加学生' }}</h3>
        <form class="student-form" @submit.prevent="submitStudentForm">
          <div class="form-row">
            <div class="form-item">
              <label>姓名</label>
              <input type="text" v-model="studentForm.name" required />
            </div>
            <div class="form-item">
              <label>性别</label>
              <select v-model="studentForm.gender" required>
                <option value="male">男</option>
                <option value="female">女</option>
              </select>
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label>年龄</label>
              <input type="number" v-model="studentForm.age" required min="10" max="18" />
            </div>
            <div class="form-item">
              <label>学号</label>
              <input type="text" v-model="studentForm.studentId" required />
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label>年级</label>
              <select v-model="studentForm.grade" required>
                <option value="初一">初一</option>
                <option value="初二">初二</option>
              </select>
            </div>
            <div class="form-item">
              <label>班级</label>
              <select v-model="studentForm.class" required>
                <option value="1">1班</option>
                <option value="2">2班</option>
              </select>
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label>联系电话</label>
              <input type="tel" v-model="studentForm.phone" required pattern="[0-9]{11}" />
            </div>
            <div class="form-item">
              <label>入学日期</label>
              <input type="date" v-model="studentForm.enrollmentDate" required />
            </div>
          </div>

          <div class="form-item">
            <label>家庭住址</label>
            <input type="text" v-model="studentForm.address" required />
          </div>

          <div class="form-row">
            <div class="form-item">
              <label>家长姓名</label>
              <input type="text" v-model="studentForm.parentName" required />
            </div>
            <div class="form-item">
              <label>家长电话</label>
              <input type="tel" v-model="studentForm.parentPhone" required pattern="[0-9]{11}" />
            </div>
          </div>

          <div class="form-item">
            <label>状态</label>
            <select v-model="studentForm.status" required>
              <option value="active">在读</option>
              <option value="suspended">休学</option>
              <option value="graduated">毕业</option>
            </select>
          </div>

          <div class="dialog-actions">
            <button type="button" class="btn btn-secondary" @click="closeStudentDialog">取消</button>
            <button type="submit" class="btn btn-primary">确定</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div class="dialog-overlay" v-if="showDeleteDialog" @click="cancelDelete">
      <div class="dialog-content" @click.stop>
        <h3>确认删除</h3>
        <p>确定要删除学生"{{ studentToDelete?.name }}"的信息吗？此操作不可恢复。</p>
        <div class="dialog-actions">
          <button class="btn btn-secondary" @click="cancelDelete">取消</button>
          <button class="btn btn-danger" @click="confirmDelete">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { studentApi } from '@/api'

export default {
  name: 'StudentManagement',
  data() {
    return {
      students: [],
      searchKeyword: '',
      filterGrade: '',
      filterClass: '',
      showStudentDialog: false,
      showDeleteDialog: false,
      isEdit: false,
      studentToDelete: null,
      studentForm: this.getInitialStudentForm()
    }
  },
  computed: {
    filteredStudents() {
      return this.students.filter((student) => {
        const matchKeyword =
          student.name.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          student.studentId.toLowerCase().includes(this.searchKeyword.toLowerCase())
        const matchGrade = !this.filterGrade || student.grade === this.filterGrade
        const matchClass = !this.filterClass || student.class === this.filterClass
        return matchKeyword && matchGrade && matchClass
      })
    }
  },
  methods: {
    getInitialStudentForm() {
      return {
        name: '',
        gender: 'male',
        age: '',
        grade: '初一',
        class: '1',
        studentId: '',
        phone: '',
        address: '',
        parentName: '',
        parentPhone: '',
        enrollmentDate: '',
        status: 'active'
      }
    },
    async fetchStudents() {
      try {
        const response = await studentApi.getStudents()
        this.students = Array.isArray(response.data) ? response.data : []

        if (this.students.length === 0) {
          this.$message.info('暂无学生数据')
        }
      } catch (error) {
        console.error('获取学生列表失败:', error)
        this.$message.error('获取学生列表失败')
        this.students = []
      }
    },
    handleSearch() {
      // 搜索和筛选逻辑由计算属性处理
    },
    openStudentDialog(student = null) {
      this.isEdit = !!student
      this.studentForm = student ? { ...student } : this.getInitialStudentForm()
      this.showStudentDialog = true
    },
    closeStudentDialog() {
      this.showStudentDialog = false
      this.studentForm = this.getInitialStudentForm()
    },
    async submitStudentForm() {
      try {
        if (this.isEdit) {
          await studentApi.updateStudent(this.studentForm.id, this.studentForm)
          this.$message.success('更新成功')
        } else {
          await studentApi.createStudent(this.studentForm)
          this.$message.success('添加成功')
        }
        await this.fetchStudents()
        this.closeStudentDialog()
      } catch (error) {
        console.error('保存学生信息失败:', error)
        this.$message.error('保存失败，请重试')
      }
    },
    deleteStudent(student) {
      this.studentToDelete = student
      this.showDeleteDialog = true
    },
    async confirmDelete() {
      if (!this.studentToDelete) return

      try {
        await studentApi.deleteStudent(this.studentToDelete.id)
        this.$message.success('删除成功')
        this.students = this.students.filter((s) => s.id !== this.studentToDelete.id)
      } catch (error) {
        console.error('删除学生失败:', error)
        this.$message.error('删除失败')
      } finally {
        this.cancelDelete()
      }
    },
    cancelDelete() {
      this.showDeleteDialog = false
      this.studentToDelete = null
    },
    getStatusText(status) {
      const statusMap = {
        active: '在读',
        suspended: '休学',
        graduated: '毕业'
      }
      return statusMap[status] || status
    }
  },
  created() {
    this.fetchStudents()
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.search-box {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-box input,
.search-box select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
  min-width: 120px;
}

.search-box input:focus,
.search-box select:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.student-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.student-table th,
.student-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

.student-table th {
  background: #f5f7fa;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
}

.student-table tr:hover {
  background: #f5f7fa;
}

.student-table td {
  color: #606266;
}

.actions {
  display: flex;
  gap: 8px;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
  line-height: 1;
}

.active {
  background: #f0f9eb;
  color: #67c23a;
}

.suspended {
  background: #fdf6ec;
  color: #e6a23c;
}

.graduated {
  background: #f4f4f5;
  color: #909399;
}

.student-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .form-item {
  flex: 1;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.form-item input,
.form-item select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
  background: #fff;
}

.form-item input:focus,
.form-item select:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-item input:hover,
.form-item select:hover {
  border-color: #c0c4cc;
}

.dialog-content {
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  position: relative;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog-content h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
}

.dialog-content p {
  margin: 0 0 24px 0;
  color: #606266;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #909399;
}

/* 添加/修改按钮样式 */
.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  text-decoration: none;
}

.btn-primary {
  background: #409eff;
  color: white;
}

.btn-primary:hover {
  background: #66b1ff;
}

.btn-secondary {
  background: #f4f4f5;
  color: #606266;
}

.btn-secondary:hover {
  background: #e9e9eb;
}

.btn-danger {
  background: #f56c6c;
  color: white;
}

.btn-danger:hover {
  background: #f78989;
}

.btn-icon {
  padding: 4px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  opacity: 0.7;
  transition: opacity 0.3s;
}

.btn-icon:hover {
  opacity: 1;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content.delete-dialog {
  width: 420px;
}

.delete-dialog p {
  color: #606266;
  line-height: 1.5;
}
</style>
